<template>
  <div class="common-list comp-orders" v-loading.fullscreen="loading">
    <div class="common-list__head">
      <el-input class="filter" v-model="filters.companyName" size="small" style="width: 320px" clearable
                placeholder="请输入" :readonly="loading" @change="search(true)" v-if="!companyId">
        <span slot="prepend">企业/项目名称</span>
      </el-input>
      <el-select class="filter" filterable v-model="filters.corpIds" size="small"
                 style="width: 240px"
                 multiple
                 clearable
                 collapse-tags
                 :filter-method="handleFilterCorp"
                 placeholder="选择企业【多选】"
                 @change="search(true)">
        <el-option
          v-for="data in corps"
          :key="data.id"
          :label="data.name"
          :value="data.id"
        ></el-option>
      </el-select>
      <el-button size="small" style="width: 120px;margin: 0 20px 20px 0;" @click="pasteCorp()">粘贴企业</el-button>
      <el-input class="filter" v-model="filters.title" size="small" style="width: 280px" clearable placeholder="请输入"
                :readonly="loading" @change="search(true)">
        <span slot="prepend">事项标题</span>
      </el-input>
      <el-input class="filter" v-model="filters.content" size="small" style="width: 280px" clearable
                placeholder="请输入" :readonly="loading" @change="search(true)">
        <span slot="prepend">事项描述</span>
      </el-input>
      <el-select class="filter" v-model="filters.tagId" size="small" style="width: 160px" @change="search(true)">
        <el-option label="不限事项分类" :value="null"></el-option>
        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
      </el-select>
      <el-input
        class="filter"
        v-model="filters.tag2"
        size="small"
        style="width: 280px"
        clearable
        placeholder="请输入"
        :readonly="loading"
        @change="search(true)"
        v-if="managerQuNums.includes(profile.number)"
      >
        <span slot="prepend">事项分类2</span>
      </el-input>
      <!-- <el-select class="filter" v-model="filters.handId" size="small" style="width: 240px" @change="search(true)">
          <el-option label="不限负责工作队" :value="null"></el-option>
          <el-option v-for="data in hands" :key="data.id" :label="data.name" :value="data.id"></el-option>
          <div class="el-select-dropdown__item" @click="chooseHand()">选择工作队</div>
      </el-select> -->

      <el-select class="filter" v-model="filters.level" size="small" style="width: 160px" @change="search(true)">
        <el-option label="不限层级" :value="null"></el-option>
        <el-option key="1" label="区县级" value="1"></el-option>
        <el-option key="2" label="市级" value="2"></el-option>
        <el-option key="3" label="自治区级" value="3"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.fwxz" size="small" style="width: 160px" @change="search(true)">
        <el-option label="不限小组" :value="null"></el-option>
        <el-option key="0" label="第一组" value="第一组"></el-option>
        <el-option key="1" label="第二组" value="第二组"></el-option>
        <el-option key="2" label="第三组" value="第三组"></el-option>
        <el-option key="3" label="第四组" value="第四组"></el-option>
        <el-option key="4" label="第五组" value="第五组"></el-option>
        <el-option key="5" label="第六组" value="第六组"></el-option>
        <el-option key="6" label="第七组" value="第七组"></el-option>
        <el-option key="7" label="第八组" value="第八组"></el-option>
        <el-option key="8" label="第九组" value="第九组"></el-option>
        <el-option key="9" label="第十组" value="第十组"></el-option>
        <el-option key="10" label="第十一组" value="第十一组"></el-option>
        <el-option key="11" label="第十二组" value="第十二组"></el-option>
        <el-option key="12" label="第十三组" value="第十三组"></el-option>
        <el-option key="13" label="第十四组" value="第十四组"></el-option>
        <el-option key="14" label="第十五组" value="第十五组"></el-option>
        <el-option key="15" label="第十六组" value="第十六组"></el-option>
        <el-option key="16" label="第十七组" value="第十七组"></el-option>
        <el-option key="17" label="厅局调研" value="厅局调研"></el-option>
        <el-option key="18" label="专项行动" value="专项行动"></el-option>
        <el-option key="19" label="领导交办事项" value="领导交办事项"></el-option>
        <el-option key="20" label="投资工作专班" value="投资工作专班"></el-option>
        <el-option key="21" label="市县自主调研" value="市县自主调研"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.deptId" size="small" style="width: 140px" @change="search(true)">
        <el-option label="不限事项层面" :value="null"></el-option>
        <el-option v-for="data in depts" :key="data.id" :label="data.name" :value="data.id"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.status" size="small" style="width: 140px" @change="search(true)"
                 v-if="!status">
        <el-option label="不限事项状态" :value="null"></el-option>
        <el-option v-for="data in env.orderStatus" :key="data.id" :label="data.name" :value="data.value"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.evaluated" size="small" style="width: 140px" @change="search(true)"
                 v-if="!evaluated">
        <el-option label="不限评价状态" :value="null"></el-option>
        <el-option v-for="data in env.orderEvaluateds" :key="data.id" :label="data.name"
                   :value="data.value"></el-option>
      </el-select>
      <el-select class="filter" filterable v-model="filters.jbdwId" size="small"
                 style="width: 140px"
                 multiple
                 clearable
                 collapse-tags
                 :filter-method="handleFilterJbdw"
                 @change="search(true)">
        <el-option label="不限经办单位" :value="null"></el-option>
        <el-option v-for="data in jbdwlist" :key="data.id" :label="data.name" :value="data.id"></el-option>
      </el-select>

      <el-select class="filter"
                 v-model="filters.belongToId"
                 size="small" style="width: 200px"
                 multiple
                 filterable
                 clearable
                 collapse-tags
                 placeholder="关联区直部门"
                 @change="search(true)">
        <el-option
          v-for="data in quDepts"
          :key="data.id"
          :label="data.name"
          :value="data.id"
        ></el-option>
      </el-select>

      <el-date-picker
        size="small"
        v-model="filters.submitTime"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="提交日期"
        end-placeholder="结束日期">
      </el-date-picker>

      <el-date-picker
        size="small"
        v-model="filters.overTime"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="完成日期"
        end-placeholder="结束日期">
      </el-date-picker>

      <el-button class="filter" type="primary" size="small" @click="search()">查询</el-button>
      <el-button class="filter" type="plain" size="small" @click="reset(true)">重置</el-button>
    </div>
    <div class="common-list__nect">
      <slot name="head" :loading="loading" :filters="filters" :selects="selects"></slot>
    </div>
    <div class="common-list__body">
      <el-table ref="table" size="medium" height="100%" :data="list" @header-click="onTableHeaderClick"
                @row-click="onTableRowClick" @selection-change="onTableSelectionChange">
        <el-table-column type="selection" align="center" v-if="select"></el-table-column>
        <el-table-column label="企业/项目信息" min-width="10" v-if="!companyId">
          <template #default="scope">
            <img style="float: left; margin-right: 10px; width: 40px; height: 40px"
                 :src="scope.row.company.logo || require('../assets/company-avatar.png')"/>
            <a :href="'#/corp/company?companyId=' + scope.row.company.id"
               v-if="link && access('corp')">{{ scope.row.company.name }}</a>
            <span v-else>{{ scope.row.company.name }}</span>
            <div style="margin-left: 50px; color: #aaa">{{ scope.row.company.typeText }}</div>
          </template>
        </el-table-column>
        <el-table-column label="事项标题" min-width="12">
          <template #default="scope">
            <a :href="'#/work/order?orderId=' + scope.row.id" v-if="link && access('work')">{{ scope.row.title }}</a>
            <span v-else>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="事项分类" min-width="6">
          <template #default="scope">
            <template v-if="scope.row.tags.length > 0">
              <div v-for="tag in scope.row.tags" :key="tag.id">{{ tag.name }}</div>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="事项分类2" min-width="6" prop="tag2" v-if="managerQuNums.includes(profile.number)">

        </el-table-column>
        <el-table-column label="服务专员" min-width="8">
          <template #default="scope">
            <!--                        <div>{{ scope.row.hand.name }}</div>-->
            <a :href="'#/org/client?clientId=' + scope.row.handler.id"
               v-if="link && access('org')">{{ scope.row.handler.name }}</a>
            <span v-else>{{ scope.row.handler.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{ scope.row.handler.number }}</span>
          </template>
        </el-table-column>
        <el-table-column label="事项层面" min-width="4">
          <template #default="scope">
            <div v-if="scope.row.level == 1 ">县级</div>
            <div v-else-if="scope.row.level == 2 ">市级</div>
            <div v-else-if="scope.row.level == 3 ">自治区级</div>
            <div v-else>
              <span v-if="scope.row.dept.county.id">县级</span>
              <span v-else-if="scope.row.dept.city.id">市级</span>
              <span v-else-if="scope.row.dept.province.id">自治区级</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事项状态" min-width="4">
          <template #default="scope">
            <span class="el-status--info" v-if="scope.row.status === 'created'"></span>
            <span class="el-status--danger"
                  v-else-if="scope.row.status === 'published' || scope.row.status === 'return'"></span>
            <span class="el-status--warning" v-else-if="scope.row.status === 'handling'"></span>
            <span class="el-status--success" v-else-if="scope.row.status === 'finished'"></span>
            <span>{{ scope.row.statusText }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评价状态" min-width="4">
          <template #default="scope">
            <span class="el-status--success"
                  v-if="scope.row.status === 'finished' && scope.row.evaluated === 'yes'"></span>
            <span class="el-status--danger"
                  v-else-if="scope.row.status === 'finished' && scope.row.evaluated === 'not'"></span>
            <span v-if="scope.row.status === 'finished'">{{ scope.row.evaluatedText }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="提交人/提交时间" min-width="6">
          <template #default="scope">
            <a :href="'#/org/client?clientId=' + scope.row.creator.id"
               v-if="link && access('org')">{{ scope.row.creator.name }}</a>
            <span v-else>{{ scope.row.creator.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{ scope.row.creator.number }}</span>
            <div style="color: #aaa">{{ scope.row.createdAt }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="160" v-if="$slots.body || $scopedSlots.body">
          <template #default="scope">
            <slot name="body" :loading="loading" :filters="filters" :data="scope.row" :selects="selects"></slot>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="common-list__foot" :class="{ 'common-list__foot--slot': $slots.foot || $scopedSlots.foot }">
      <el-pagination background layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 50, 100]"
                     :page-size="filters.linage" :current-page="filters.page" :total="filters.total"
                     @size-change="onTableLinageChange" @current-change="onTablePageChange"></el-pagination>
      <slot name="foot" :loading="loading" :filters="filters" :selects="selects"></slot>
    </div>
    <comp-dialog title="选择工作队" width="720px" height="80vh" ref="deptPicker">
      <comp-depts style="height: 100%" ref="deptPickerList" expanded>
        <template #body="scope">
          <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="chooseHand('submit', scope.data)"
                     v-if="scope.data.type === 'team' || scope.data.type === 'office'">选择
          </el-button>
        </template>
        <template #foot>
          <el-button type="danger" size="small" icon="el-icon-close" @click="chooseHand('end')">放弃</el-button>
        </template>
      </comp-depts>
    </comp-dialog>

    <comp-dialog title="粘贴企业" width="720px" height="80vh" ref="corpPicker">
      <el-row>
        <el-col :span="24">
          <span>输入/粘贴企业名称-可以多行</span>
        </el-col>
      </el-row>
      <el-input type="textarea"
                :rows="8"
                v-model="filters.corpNames"
                @input="pasteCorp('change')"
                style="margin-top:5px;"
                placeholder="输入/粘贴企业名称-可以多行">

      </el-input>
      <el-divider/>
      <div class="orderCorpSelect">
        <el-transfer v-model="filters.selectCorps"
                     :titles="['候选','选中']"
                     :props="{
                      key: 'id',
                      label: 'name'
                    }"
                     :data="filters.dataCorps"
                     style="margin: 0 auto;"
                     :render-content="pasteCorpRender"
        ></el-transfer>
      </div>
      <el-divider/>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="pasteCorp('submit')">确定</el-button>
          <el-button type="danger" size="small" icon="el-icon-close" @click="pasteCorp('end')">放弃</el-button>
        </el-col>
      </el-row>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import {object, array, string, int, session} from "../util";

export default {
  name: "comp-orders",
  mixins: [mixin],
  props: {
    companyId: {type: String, default: null},
    evaluated: {type: String, default: null},
    status: {type: String, default: null},
    select: {type: Boolean, default: false},
    link: {type: Boolean, default: false},
  },
  data: () => ({
    loading: false,
    filters: {
      ids: null,
      corpIds: null,
      corpNames: null,
      corpName: null,
      companyId: null,
      companyName: null,
      title: null,
      content: null,
      deptId: null,
      handId: null,
      evaluated: null,
      jbdwId: null,
      status: null,
      level: null,
      fwxz: null,
      linage: 10,
      page: 1,
      total: 0,
      submitTime: undefined,
      overTime: undefined,
      tag2: undefined,
      belongToId: [],
      selectCorps: [],
      dataCorps: [],
    },
    list: [],
    selects: [],
    tags: [],
    depts: [],
    hands: [],
    jbdwlist: [],
    jbdwlistAll: [],
    quDepts: [],
    managerQuNums: managerQuNums,
    corps: []
  }),
  methods: {
    reset(deep) {
      let data = deep ? {} : object(session([this.env.key, this.$options.name, "filters", this.$route.fullPath]));
      this.filters = Object.assign(this.$options.data().filters, data);
      this.hands = array(session([this.env.key, this.$options.name, "hands", this.$route.fullPath]));
      this.pasteCorp('corpIds-init')
      this.search(true);
    },
    validate() {
      let filters = this.filters;
      let tags = this.tags;
      let hands = this.hands;
      filters.ids = null;
      filters.tagId = string(() => tags.find((tag) => tag.id === filters.tagId).id) || null;
      filters.companyId = this.companyId;
      filters.companyName = this.companyId ? null : filters.companyName;
      filters.handId = string(() => hands.find((dept) => dept.id === filters.handId).id) || null;
      filters.evaluated = this.evaluated || filters.evaluated;
      filters.status = this.status || filters.status;
      filters.total = Math.max(int(filters.total), 0);
      filters.linage = Math.max(int(filters.linage), 1);
      filters.level = this.level || filters.level;
      filters.page = Math.max(Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)), 1);
      session([this.env.key, this.$options.name, "filters", this.$route.fullPath], filters);
      session([this.env.key, this.$options.name, "hands", this.$route.fullPath], hands);
    },
    onTableHeaderClick() {
      this.select && this.$refs.table.toggleAllSelection();
    },
    onTableRowClick(row) {
      this.select && this.$refs.table.toggleRowSelection(row);
    },
    onTableLinageChange(value) {
      this.filters.linage = value;
      this.search(true);
    },
    onTablePageChange(value) {
      this.filters.page = value;
      this.search(true);
    },
    onTableSelectionChange(selects) {
      this.filters.ids = selects.map((data) => data.id);
      this.selects = selects;
    },
    chooseHand(action, dept) {
      if (this.loading) return;
      let filters = this.filters;
      if (!action || action === "start") {
        this.$refs.deptPicker.init();
        this.$nextTick(() => this.$refs.deptPickerList.init());
      } else if (action === "submit") {
        let index = this.hands.findIndex((target) => target.id === dept.id);
        if (index > -1) this.hands.splice(index, 1);
        filters.handId = dept.id;
        this.hands.push({id: dept.id, name: dept.name});
        this.chooseHand("end");
        this.search(true);
      } else if (action === "end") {
        this.$refs.deptPicker.close();
      }
    },
    async pasteCorp(action, data) {
      if (this.loading) return;
      if (!action || action === "start") {
        this.filters.selectCorps = []
        this.filters.dataCorps = []
        this.filters.corpNames = null;
        this.$refs.corpPicker.init();
        let corpResult = await this.plugins.user.getCompanys({
          pageSize: 10,
          pageNum: 1,
        })
        this.filters.dataCorps = corpResult?.data?.list || []
      } else if (action === "change") {
        const names = this.filters.corpNames.split('\n')
        let corps = []
        for (let i = 0; i < names.length; i++) {
          let corpResult = await this.plugins.user.getCompanys({
            pageSize: 10,
            pageNum: 1,
            name: names[i]
          })
          corps = corps.concat(corpResult?.data?.list)
        }
        const ids = this.filters.selectCorps.concat(corps.map(x => x.id))
        this.filters.dataCorps = this.filters.dataCorps.concat(corps).filter(x => ids.includes(x.id))
        this.filters.dataCorps = Array.from(new Set(this.filters.dataCorps.map(x => x.id))).map(id => this.filters.dataCorps.find(x => x.id == id))
      } else if (action === "corpIds-init") {
        const ids = this.filters.corpIds
        let corps = []
        if (ids?.length > 0) {
          let corpResult = await this.plugins.user.getCompanys({
            pageSize: 10,
            pageNum: 1,
            ids: ids
          })
          if (corpResult?.data?.list?.length > 0) {
            corps = corps.concat(corpResult?.data?.list)
          }
        }
        this.corps = corps
        this.pasteCorp('end')
      } else if (action === "submit") {
        this.filters.corpIds = this.filters.selectCorps
        this.corps = this.filters.dataCorps.filter(x => this.filters.selectCorps.includes(x.id))
        this.$nextTick(() => {
          this.search()
        })
        this.pasteCorp('end')
      } else if (action === "end") {
        this.$refs.corpPicker.close();
      }
    },
    pasteCorpRender(h, option) {
      return <el-tooltip className="item" effect="dark" content={option.name} placement="left">
        <span>{option.name}</span>
      </el-tooltip>
    },
    search(clean) {
      if (this.loading) return;
      if (clean) this.list = [];
      if (clean) this.selects = [];
      let filters = this.filters;
      this.validate();
      this.loading = true;
      filters.createdTimeStart = filters.submitTime?.[0];
      filters.createdTimeEnd = filters.submitTime?.[1];
      let createdTimeEnd = filters.submitTime?.[1] || null
      if (createdTimeEnd) {
        if (typeof (createdTimeEnd) == 'string') {
          createdTimeEnd = new Date(createdTimeEnd)
        }
        createdTimeEnd = new Date(createdTimeEnd.getTime() + 24 * 60 * 60 * 1000).formatDate('yyyy-MM-dd')
      }

      filters.completeTimeStart = filters.overTime?.[0];
      filters.completeTimeEnd = filters.overTime?.[1];
      let completeTimeEnd = filters.overTime?.[1] || null
      if (completeTimeEnd) {
        if (typeof (createdTimeEnd) == 'string') {
          completeTimeEnd = new Date(completeTimeEnd)
        }
        completeTimeEnd = new Date(completeTimeEnd.getTime() + 24 * 60 * 60 * 1000).formatDate('yyyy-MM-dd')
      }
      console.log('search', filters)
      let jbdwIds = (filters.jbdwId ? filters.jbdwId : []).concat(this.jbdwlistAll.filter(x => x.belongToId && this.filters.belongToId?.includes(x.belongToId)).map(x => x.id))
      if (this.filters.belongToId) {
        jbdwIds = jbdwIds.concat(this.filters.belongToId)
      }
      this.plugins.user.getOrders({
        ...filters,
        createdTimeEnd,
        completeTimeEnd,
        jbdwId: jbdwIds && jbdwIds.length > 0 ? jbdwIds : null,
      }).then((res) => {
        this.loading = false;
        this.list = [];
        this.selects = [];
        this.$nextTick(() => this.$refs.table.doLayout());
        if (res.code === 0) {
          let data = res.data;
          if (data.page > 1 && data.list.length === 0) {
            filters.total = 0;
            this.search();
          } else {
            filters.total = data.total;
            this.list = data.list;
            this.validate();
          }
        } else {
          filters.total = 0;
          this.validate();
          this.plugins.modal.toast("列表加载失败<br>" + res.code + "：" + res.msg, "error");
        }
      });
    },
    init() {

      this.loading = true;
      this.plugins.user.call(async () => {
          const res = await this.plugins.user.getDepts({linage: 10000000, page: 1})
          this.jbdwlistAll = res.data.list.map(x => {
            return {
              id: x.id,
              name: x.name,
              belongToId: x.belongToId,
              parentId: x.parentId
            }
          });
          this.quDepts = res.data.list?.filter(x => x.parentId === '202216425835730001')
          // 给10条默认就行了
          this.jbdwlist = res.data.list.map(x => {
            return {
              id: x.id,
              name: x.name
            }
          }).slice(1, 10).concat(this.jbdwlistAll.filter(x => this.filters.jbdwId?.includes(x.id)));
          return {code: 0}
        }
        , async () => {
          let length = this.tags.length;
          if (length === 0) this.tags = await this.plugins.user.getOrderOfTags({
            linage: 100,
            page: 1
          }).then((res) => array(() =>
            res.data.list
          ));
          return {code: 0};
        }, async () => {

          let length = this.depts.length;

          if (length === 0) this.depts = await this.plugins.user.getDepts({
            level: 1,
            linage: 1000,
            page: 1
          }).then((res) => {

            let dept = array(() => res.data.list).find((dept) => dept.type === "office" && dept.province.id === "450000" && !dept.city.id && !dept.county.id);
            return dept ? [{id: dept.id, name: "自治区级"}] : [];
          });

          return {code: 0};
        }).then((res) => {
        this.loading = false;
        this.reset();
      });
    },
    handleFilterJbdw(e) {
      console.log(e)
      if (e && e.length > 0) {
        this.jbdwlist = this.jbdwlistAll.filter(x => x.name.includes(e) || this.filters.jbdwId?.includes(x.id)).slice(0, 200)
      }
    },
    handleFilterCorp(e) {
      console.log('过滤企业', e)
      // 过滤企业
      this.plugins.user.getCompanys({
        name: e || null,
        pageSize: 10,
        pageNum: 1
      }).then(res => {
        this.corps = res.data.list
      })
    }
  },
};
</script>

<style lang="scss">
.comp-orders {
  overflow: hidden;
}

.orderCorpSelect .el-transfer-panel__header .el-checkbox__label span{
  right: -100px !important;
}
</style>
